import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error

#糖尿病人数据
diabetes = datasets.load_diabetes()
#查看diabetes结构
print(diabetes.feature_names)
diabetes_X = diabetes.data[:,np.newaxis,2]
#diabetes_X = diabetes_X.reshape(len(diabetes_X),1)
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
#创建一个线性回归对象
regr = linear_model.LinearRegression()
#用训练数据训练模型
regr.fit(diabetes_X_train, diabetes_y_train)
#用训练好的模型对测试集上的数据进行预测
diabetes_y_pred = regr.predict(diabetes_X_test)
print('Coefficients: \n', regr.coef_)
print("Mean squared error: %.2f"
      % mean_squared_error(diabetes_y_test, diabetes_y_pred))
#可视化展示
plt.scatter(diabetes_X_test, diabetes_y_pred,  color='red')
plt.scatter(diabetes_X_test, diabetes_y_test,  color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.show()